<template>
  <div>
    <el-dialog
      v-model="courseDialogForm"
      :title="action ==='post' ? '添加章节' : '编辑章节'"
      width="600px"
      @closed="closed"
    >
      <el-form
        v-if="action === 'put'"
        ref="ruleFormRef"
        :model="editForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
      >
        <el-form-item label="章节名称" prop="title">
          <el-input v-model="editForm.title"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="editForm.sort"/>
        </el-form-item>
      </el-form>
      <el-form
        v-else-if="action === 'post'"
        ref="ruleFormRef"
        :model="courseForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
      >
        <el-form-item label="章节名称" prop="title">
          <el-input v-model="courseForm.title"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="courseForm.sort"/>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="addOrEditCourse(ruleFormRef)">确认</el-button>
            <el-button type="primary" @click="courseDialogForm = false">取消</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts' setup>
import {
  ref, defineExpose, reactive, defineProps, getCurrentInstance,
} from 'vue';
import type { UploadInstance } from 'element-plus';
import {
  ElMessage, FormInstance, FormRules,
} from 'element-plus';
import { useRoute } from 'vue-router';
import Request from '@/api/request/request';

// 定义接口类型
type Props = {
  title?: string,
  courseFormId?: number
  chapter?: any,
  action?: string,
}
const props = defineProps<Props>();
const route = useRoute();
const { proxy } = getCurrentInstance();

const editForm = ref({
  id: '',
  title: '',
  sort: '',
  courseId: route.params.CourseId,
});
// 添加章节form表单
const ruleFormRef = ref<FormInstance>();
const courseForm = ref({
  id: '',
  title: '',
  sort: 1,
  courseId: route.params.CourseId,
});
// 校验规则
const rules = reactive<FormRules>({
  title: [{
    required: true,
    message: '请输入章节名称',
    trigger: 'blur',
  },
  {
    min: 1,
    max: 20,
    message: '标题长度为必须在2-20之间',
    trigger: 'blur',
  }],
  sort: [{
    required: true,
    message: '请输入排序',
    trigger: 'blur',
  }],
});
// 添加弹窗控制
// 添加章节弹窗控制
const courseDialogForm = ref<boolean>(false);
// 一级章节id
const chapterMainId = ref<number>();
// element-plus用于重置表单
const uploadRef = ref<UploadInstance>();

// 关闭对话框时候
const closed = () => {
  // 重置表单
  ruleFormRef.value!.resetFields();
};

// 添加课程章节
const addOrEditCourse = async (formEl: FormInstance | undefined) => {
  const courseId = sessionStorage.getItem('courseId');
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      if (props.action === 'put') {
        let result: any = await new Request(`${proxy.$urls.API_URL_BACKSTAGE_SCHOOLCOURSESECTION_MANAGE}`, {
          id: editForm.value.id,
          title: editForm.value.title,
          sort: editForm.value.sort,
          courseId,
        }).put();
        if (result.success) {
          ElMessage.success('编辑成功');
          proxy.$emit('load');
          courseDialogForm.value = false;
        } else {
          ElMessage.error('编辑失败');
        }
      } else if (props.action === 'post') {
        // 判断传过来的章节父id是否为空，如果不为空则添加二级章节，如果为空则是添加一级章节
        const parentId = props.courseFormId;
        if (parentId != null) {
          let result: any = await new Request(`${proxy.$urls.API_URL_BACKSTAGE_SCHOOLCOURSESECTION_MANAGE}`, {
            parentId,
            title: courseForm.value.title,
            sort: courseForm.value.sort,
            courseId,
          }).post();
          if (result.success) {
            ElMessage.success('添加成功');
            proxy.$emit('load');
            courseDialogForm.value = false;
          } else {
            ElMessage.error('添加失败');
          }
        } else {
          let result: any = await new Request(`${proxy.$urls.API_URL_BACKSTAGE_SCHOOLCOURSESECTION_MANAGE}`, {
            title: courseForm.value.title,
            sort: courseForm.value.sort,
            courseId,
          }).post();
          if (result.success) {
            ElMessage.success('添加成功');
            proxy.$emit('load');
            courseDialogForm.value = false;
          } else {
            ElMessage.error('添加失败');
          }
        }
      }
    }
  });
};

const openDialog = () => {
  courseDialogForm.value = true;
};

const editDialog = async (id:number) => {
  let result: any = await new Request(`${proxy.$urls.API_URL_BACKSTAGE_SCHOOLCOURSESECTION_MANAGE}/${id}`).get();
  editForm.value = result.data;
  courseDialogForm.value = true;
};

defineExpose({
  openDialog,
  editDialog,
});
</script>

<style scoped>

</style>
